package com.oj.util;

import com.oj.entity.OnlineUser;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class OnlineUserUtil {
    private static Map<String, OnlineUser> map_online_users = Collections.synchronizedMap(new HashMap<String, OnlineUser>());

    public static boolean userOnline(String username) {
        if (username == null){
            return false;
        }

        if (true == map_online_users.containsKey(username)){
            OnlineUser ou = map_online_users.get(username);
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ou.setLastAccessTime(Timestamp.valueOf(simpleDate.format(new Date())));
            ou.setOnline(1);
        }
        else{
            OnlineUser ou = new OnlineUser();
            ou.setUsername(username);
            map_online_users.put(username, ou);
            log.info(username + " add to online list.");
        }

        return true;
    }

    public static boolean userOffline(String username) {
        if (username == null){
            return false;
        }

        log.info(username + " offline from online list.");
        if (true == map_online_users.containsKey(username)) {
            OnlineUser ou = map_online_users.get(username);
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ou.setLastAccessTime(Timestamp.valueOf(simpleDate.format(new Date())));
            ou.setOnline(0);
        }

        return true;
    }

    public static int size() {
        return map_online_users.size();
    }

    public static OnlineUser getUser(String username){
        return map_online_users.get(username);
    }

    public static Map<String, OnlineUser> getOnlineUsers() {
        return map_online_users;
    }
}
